#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
已处理文件管理器
用于管理已成功处理的PDF文件，避免重复处理
"""

import json
from pathlib import Path
from typing import Set, Dict, Any
from ..utils import ToolbeltLogger


class ProcessedFilesManager:
    """已处理文件管理器"""
    
    def __init__(self, processed_files_path: Path):
        """
        初始化已处理文件管理器
        
        Args:
            processed_files_path (Path): 已处理文件记录的JSON文件路径
        """
        self.processed_files_path = processed_files_path
        self.processed_files: Dict[str, Dict[str, Any]] = {}
        self._load_processed_files()
    
    def _load_processed_files(self) -> None:
        """从JSON文件加载已处理的文件信息"""
        if self.processed_files_path.exists():
            try:
                with open(self.processed_files_path, 'r', encoding='utf-8') as f:
                    self.processed_files = json.load(f)
                ToolbeltLogger.info(f"已加载 {len(self.processed_files)} 个已处理文件记录")
            except Exception as e:
                ToolbeltLogger.warning(f"无法读取已处理文件记录 {self.processed_files_path}: {e}")
                self.processed_files = {}
        else:
            self.processed_files = {}
    
    def _save_processed_files(self) -> None:
        """将已处理的文件信息保存到JSON文件"""
        try:
            # 确保目录存在
            self.processed_files_path.parent.mkdir(parents=True, exist_ok=True)
            
            with open(self.processed_files_path, 'w', encoding='utf-8') as f:
                json.dump(self.processed_files, f, ensure_ascii=False, indent=2)
            ToolbeltLogger.debug(f"已保存已处理文件记录到 {self.processed_files_path}")
        except Exception as e:
            ToolbeltLogger.warning(f"无法保存已处理文件记录 {self.processed_files_path}: {e}")
    
    def is_file_processed(self, filename: str) -> bool:
        """
        检查文件是否已处理
        
        Args:
            filename (str): 文件名
            
        Returns:
            bool: 如果文件已处理则返回True，否则返回False
        """
        return filename in self.processed_files
    
    def add_processed_file(self, filename: str, summary_data: Dict[str, Any]) -> None:
        """
        添加已处理的文件
        
        Args:
            filename (str): 文件名
            summary_data (Dict[str, Any]): 总结数据
        """
        self.processed_files[filename] = {
            "filepath": summary_data.get("filepath", ""),
            "processed_time": summary_data.get("processed_time", ""),
            "summary": summary_data.get("summary", "")
        }
        self._save_processed_files()
    
    def get_processed_files(self) -> Set[str]:
        """
        获取所有已处理的文件名
        
        Returns:
            Set[str]: 已处理的文件名集合
        """
        return set(self.processed_files.keys())